package com.bridgeintelligent.tag.interceptors;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import java.io.*;

/**
 * @Author：liwei
 * @Date：2023/9/21 11:01
 * @Desc：
 */
@Slf4j
public class MultiReadHttpServletRequestWrapper extends HttpServletRequestWrapper {

    // We include a max byte size to protect against malicious requests,
    //since this all has to be read into memory
    public static final Integer MAX_BYTE_SIZE = 1024*1024; // 1 MB

    private String body;

    public MultiReadHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);

        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            InputStream inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
                char[] charBuffer = new char[1024];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            }
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    throw ex;
                }
            }
        }
        body = stringBuilder.toString();
        log.info("====================>body:{}",body);
    }


    @Override
    public ServletInputStream getInputStream() throws IOException{
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes("UTF-8"));
        return new ServletInputStream() {
            @Override
            public int read() {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                return byteArrayInputStream.available() == 0;//byteArrayInputStream.available() == 0
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener listener) {

            }
        };
    }

    @Override
    public BufferedReader getReader()throws IOException  {
        return new BufferedReader(new InputStreamReader(this.getInputStream(),"UTF-8"));
    }

    /**
     * 获取body
     * @return
     */
    public String getBody() {
        return this.body;
    }
}

